package com.stark.wechat.controller;

import java.net.URLDecoder;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stark.wechat.form.Result;
import com.stark.wechat.service.impl.TicketServiceImpl;

/**
 * 微信票据控制器。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0, 2017/8/5
 */
@Controller
public class TicketController {
	Logger logger = LoggerFactory.getLogger(TicketController.class);
	
	@Autowired
	private TicketServiceImpl ticketService;
	
	/**
	 * 生成 JS-SDK 签名。
	 * @param url 调用 JS 接口页面的完整 URL ，不包含 # 及其后面部分。
	 * @return {@link Result} 对象。请求成功时 {@link Result#getData()} 中包含属性：
	 * (String) noncestr 、 (String) jsapiTicket 、 (long) timestamp 、 (String) signature 、 (String) appId 。
	 * @throws Exception 请求失败时抛出异常。
	 */
	@PostMapping("/ticket/jsapiTicket")
	@ResponseBody
	public Result createJsapiTicket(String url) {
		try {
			url = URLDecoder.decode(url, "UTF-8");
			Map<String, Object> map = this.ticketService.createJsSdkSignature(url);
			
			return Result.success()
					.addData("noncestr", (String) map.get("noncestr"))
					.addData("jsapiTicket", (String) map.get("jsapiTicket"))
					.addData("timestamp", (Long) map.get("timestamp"))
					.addData("signature", (String) map.get("signature"))
					.addData("appId", (String) map.get("appId"));
		} catch (Exception e) {
			logger.error("生成 JS-SDK 签名时出错：url={}", url, e);
			return Result.fail().errmsg(e.getMessage());
		}
	}
}
